<!--  -->
<template>
    <div>
<!--内容-->
<div id="waypoint" class="m-container m-pad-tb-big m-opacity animated fadeIn">
    <div class="ui container ">
        <!--博客-->
        <div class="ui top attached segment">
            <!--博客头部-->
            <div class="ui container center aligned">
                <h1 class="ui header m-pad-tb-blog-head">{{blog.title}}</h1>
                <div class="ui horizontal link list middle aligned">
                    <div class="ui item left aligned ">
                        <div class="ui orange label basic teal">{{blog.flag}}</div>
                    </div>
                    <div class="item">
                        <i class="calendar icon "></i><span>{{blog.updateTime | formatDate("YYYY-MM-DD")}}</span>
                    </div>
                    <div class="item">
                        <i class="idea icon"></i><span>{{blog.type.name}}</span>
                    </div>
                    <div class="item">
                        <i class="eye icon"></i><span>{{blog.views}}</span>
                    </div>
                    <div class="item">
                        <i class="comment outline icon"></i><span>{{blog.commentCount}}</span>
                    </div>
                </div>
            </div>
            <!--博客内容-->
            <div id="content" class="typo typo-selection m-pad-tb-huge m-pad-lr js-toc-content m-text" v-html="blog.content">
            </div>
        </div>
        <!--博客信息-->
        <div class="ui attached positive message m-pad-tb-large" v-if="blog.shareStatement">
            <div class="ui grid">
                <div class="eleven wide column">
                    <ul class="list">
                        <li>作者：<span>山内有樱名为良</span></li>
                        <li>发表时间：<span>{{blog.updateTime | formatDate("YYYY-MM-DD")}}</span></li>
                        <li>版权声明：自由转载-非商用-非衍生-保持署名（创意共享3.0许可证）</li>
                        <li>转载声明：如果是转载博主文章，请附上原文链接</li>
                    </ul>
                </div>
            </div>
        </div>
        <!--留言区-->
        <div class="ui bottom attached segment " v-if="blog.commentable">
            <div class="ui teal segment" id="comment-container">
                <div class="ui threaded comments" style="max-width: 100%;">
                    <h3 class="ui dividing header">评论</h3>
                    <div class="comment" v-for="comment in comments" :key="comment.id">
                        <a class="avatar">
                            <img src="../../assets/images/avatar.png">
                        </a>
                        <div class="content">
                            <a class="author">
                                <span>{{comment.nickname}}</span>
                                <div class="ui mini basic teal label m-pad-tb-mini" v-if="comment.adminComment">博主</div>
                            </a>
                            <div class="metadata">
                                <span class="date">{{comment.createTime | formatDate("YYYY-MM-DD HH:mm")}}</span>
                            </div>
                            <div class="text" >
                                {{comment.content}}
                            </div>
                            <div class="actions">
                                <a class="reply" @click="replyComment(comment.id,comment.nickname)">回复</a>
                                <a v-if="admin" @click="deleteComment(comment.id)">删除</a>
                            </div>
                        </div>
                        <!--子集评论-->
                        <div class="comments" v-if="comment.replyComments.length>0">
                            <div class="comment" v-for="reply in comment.replyComments" :key="reply.id">
                                <a class="avatar">
                                    <img src="../../assets/images/avatar.png">
                                </a>
                                <div class="content">
                                    <a class="author" >
                                        <span>{{reply.nickname}}</span>
                                        <div class="ui mini basic teal label m-pad-tb-mini" v-if="reply.adminComment">博主</div>
                                        &nbsp;<span class="m-teal">{{"@ "+reply.parentCommentNickname}}</span>
                                    </a>
                                    <div class="metadata">
                                        <span class="date">{{reply.createTime | formatDate("YYYY-MM-DD HH:mm")}}</span>
                                    </div>
                                    <div class="text">
                                        {{reply.content}}
                                    </div>
                                    <div class="actions">
                                        <a class="reply" @click="replyComment(reply.id,reply.nickname)">回复</a>
                                        <a v-if="admin" @click="deleteComment(reply.id)">删除</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="comment-form" class="ui form">
                <div class="field" id="field-content">
                    <textarea v-model="theComment.content" placeholder="请输入评论。。。" name="content"></textarea>
                </div>
                <div class="fields">
                    <div class="field" id="field-nickname">
                        <div class="ui left icon input">
                            <i class="user icon"></i>
                            <input type="text"  v-model="theComment.nickname" placeholder="姓名" name="nickname">
                        </div>
                    </div>
                    <div class="field" id="field-email">
                        <div class="ui left icon input">
                            <i class="mail icon"></i>
                            <input type="text" v-model="theComment.email" placeholder="邮箱" name="email">
                        </div>
                    </div>
                    <div class="field">
                        <button @click="submitComment" class="ui teal button"><i class="edit icon"></i>发布</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="toolbar" class="m-pad-lr-large m-margin-tb-large m-fixed m-right-bottom" style="display:none;">
    <div class="ui vertical icon buttons">
        <router-link class="ui teal button" to="/index">首页</router-link>
        <div class="ui teal button" @click="toComment">评论</div>
        <div class="ui icon button" @click="toTop"><i class="chevron up icon"></i></div>
    </div>
</div>
<br>
    </div>
</template>

<script>
import "../../assets/lib/waypoints/jquery.waypoints.js"
import Prism from "prismjs";

export default {
	props:['id'],
    data () {
        return {
			blog:{
				type:{
				}
			},
            comments:{

            },
            theComment:{
                parentCommentId:-1,
                blogId:this.id,
                nickname:"",
                email:"",
                content:""
            },
            admin : localStorage.getItem('user') ? true : false,
            ImgDomainName:this.$ImgDomainName
        };
    },
    methods:{
        toTop(){
            $(window).scrollTo(0,500);
        },
        toComment(){
            $.scrollTo('#comment-container',500);
        },
        getComments(){
            var _this = this
            _this.axios.get("/getComments",{
                params:{
                    blogId:_this.id
                }
            }).then((res) => {
                _this.comments = res.data.comments
            }).catch((err) => {
                consolo.log(err)
            });
        },
        submitComment(){
            //表单验证
            //以下三个为动画效果
            this.ValidationEmpty('content')
            this.ValidationEmpty('nickname')
            this.ValidationEmail('email')
            //以下两个if为验证拦截
            if(this.theComment.content.length==0||this.theComment.nickname.length==0)
                return
            var pattern = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/
            if(this.theComment.email.length==0||!pattern.test(this.theComment.email))
                return
            var _this = this
            _this.axios.post("/saveComment",{
                parentCommentId:_this.theComment.parentCommentId,
                blogId:_this.id,
                nickname:_this.theComment.nickname,
                email:_this.theComment.email,
                content:_this.theComment.content,
                adminComment:_this.admin
            }).then(res=>{
                if(res.data.status===200){
                    _this.getComments()
                    _this.clearContent()
                }else{
                    alert(res.data.msg)
                }
            }).catch(e=>{

            })
        },
        deleteComment(commentId){
            if(confirm("确认要删除该条评论吗")){
                var _this =this
                _this.axios.get("/deleteComment",{
                    params:{
                        commentId:commentId
                    }
                }).then(res=>{
                    if(res.data.status===200){
                        _this.getComments()
                    }else{
                        alert(res.data.msg)
                    }
                }).catch(e=>{
                    console.log(e)
                })
            }
        },
        //非空验证
        ValidationEmpty(str){
            var f = function(str){
                var val = $("[name='"+str+"']").val()
                if(val.length>0){
                    $("#field-"+str).removeClass('error')
                    clearInterval(t_f)
                }else{
                    $("#field-"+str).addClass('error')
                }
            }
            var t_f = setInterval(f,10,str)
        },
        //邮箱验证
        ValidationEmail(str){
            var pattern = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/
            var f = function(str){
                var val = $("[name='"+str+"']").val()
                if(val.length>0&&pattern.test(val)){
                    $("#field-"+str).removeClass('error')
                    $(window).scrollTo($('#comment-container'),500);
                    clearInterval(t_f)
                }else{
                    $("#field-"+str).addClass('error')
                }
            }
            var t_f = setInterval(f,10,str)
        },
        clearContent() {
            this.theComment.nickname=""
            this.theComment.email=""
            this.theComment.content=""
            this.theComment.parentCommentId=-1
            $("[name='content']").attr("placeholder","请输入评论。。。");
        },
        replyComment(commentId,commentNickname) {
            $("[name='content']").attr("placeholder","@"+commentNickname).focus();
            this.theComment.parentCommentId=commentId
            $(window).scrollTo($('#comment-form'),500);
        }
    },
	created(){
        var _this = this
        
        //管理员用户
        if(localStorage.getItem('user')!=null){
            var adminInfo = localStorage.getItem('user')
            adminInfo = JSON.parse(adminInfo)
            _this.theComment.nickname = adminInfo.nickname
            _this.theComment.email = adminInfo.email
        }
        //得到评论信息
        _this.getComments()
		//得到博客信息
		_this.axios.get("/getShowBlogById",{
			params:{
				id:_this.id
			}
		}).then((res) => {
			if(res.data.status ===200){
                _this.blog = res.data.blog
                this.$nextTick(()=>{
                    
                    $('.typo img').css("max-width","100%")

                    Prism.highlightAll()
                })
			}else{
				//查询不到，跳转到404
				_this.$router.push({path:"/404"})
            }
		}).catch((err) => {
			console.log(err)
        })
	},
    mounted(){
        $(window).scrollTo(0)
        //滚动监听
        var waypoint = new Waypoint({
            element: document.getElementById('waypoint'),
            handler: function(direction) {
                if (direction == 'down') {
                    $('#toolbar').show(200);
                }
                else{
                    //500为时间间隔
                    $('#toolbar').hide(500);
                }
            }
        })
        //评论表单验证规则
        $('.ui.form').form({
            fields:{
                content : {
                    identifier:'content',
                    rules:[{
                        type:'empty',
                    }]
                },
                nickname : {
                    identifier:'nickname',
                    rules:[{
                        type:'empty',
                    }]
                },
                email : {
                    identifier:'email',
                    rules:[{
                        type:'email',
                    }]
                }
            }
        });
    }
}

</script>
<style scoped>
@import "../../assets/css/typo.css";
</style>

